package com.lineage.data.npc.quest2;

import com.lineage.data.QuestClass;
import com.lineage.data.executor.NpcExecutor;
import com.lineage.data.quest.ADLv80_3;
import com.lineage.server.datatables.InnKeyTable;
import com.lineage.server.datatables.InnTable;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.datatables.QuestMapTable;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1MonsterInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.item.L1ItemId;
import com.lineage.server.model.L1GroundInventory;
import com.lineage.server.model.L1Inventory;
import com.lineage.server.model.L1PcInventory;
import com.lineage.server.model.L1Teleport;
import com.lineage.server.model.skill.L1SkillMode;
import com.lineage.server.model.skill.skillmode.SkillMode;
import com.lineage.server.serverpackets.S_BlueMessage;
import com.lineage.server.serverpackets.S_CloseList;
import com.lineage.server.serverpackets.S_NPCTalkReturn;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.S_SkillSound;
import com.lineage.server.serverpackets.S_SystemMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1Inn;
import com.lineage.server.templates.L1QuestUser;
import com.lineage.server.utils.L1SpawnUtil;
import com.lineage.server.world.World;
import com.lineage.server.world.WorldQuest;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Npc_DragonA3 extends NpcExecutor {
	private static final Log _log = LogFactory.getLog(Npc_DragonA3.class);

	private Map<Integer, ArrayList<Integer>> _DOORPLAYERMAP = new HashMap<>();

	private ArrayList<Integer> key_runout_doorid = new ArrayList<>();

	public static NpcExecutor get() {
		return new Npc_DragonA3();
	}

	public int type() {
		return 3;
	}

	public void talk(L1PcInstance pc, L1NpcInstance npc) {
		try {
			pc.sendPackets(
					(ServerBasePacket) new S_NPCTalkReturn(npc.getId(), "y_n_dragon1", new String[] { "林德拜尔栖息地" }));
		} catch (Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		}
	}

	public void action(L1PcInstance pc, L1NpcInstance npc, String cmd, long amount) {
		if (cmd.equalsIgnoreCase("0")) {
			if (isError2(pc, npc))
				return;
			int npcId = npc.getNpcTemplate().get_npcId();
			Iterator<L1ItemInstance> iterator = pc.getInventory().getItems().iterator();
			while (iterator.hasNext()) {
				L1ItemInstance item = iterator.next();
				if (item.getInnNpcId() == npcId) {
					int i = 0;
					while (i < 16) {
						L1Inn inn = InnTable.getInstance().getTemplate(npcId, i);
						if (inn.getKeyId() == item.getKeyId()) {
							Timestamp dueTime = item.getDueTime();
							if (dueTime != null) {
								Calendar cal = Calendar.getInstance();
								if ((cal.getTimeInMillis() - dueTime.getTime()) / 1000L < 0L) {
									pc.set_showId(item.getKeyId());
									staraQuestA(npc, pc);
									break;
								}
							}
						}
						i++;
					}
				}
			}
		}
		if (cmd.equalsIgnoreCase("1")) {
			amount = 32L;
			int npcId = npc.getNpcTemplate().get_npcId();
			boolean canRent = false;
			boolean findRoom = false;
			boolean isRented = false;
			int roomNumber = 0;
			byte roomCount = 0;
			int j = 0;
			while (j < 16) {
				L1Inn inn2 = InnTable.getInstance().getTemplate(npcId, j);
				if (inn2 != null) {
					Timestamp dueTime2 = inn2.getDueTime();
					Calendar cal2 = Calendar.getInstance();
					long checkDueTime = (cal2.getTimeInMillis() - dueTime2.getTime()) / 1000L;
					if (pc.getInventory().checkItem(82504, 1L)) {
						isRented = true;
						break;
					}
					if (!findRoom && !isRented)
						if (checkDueTime >= 0L) {
							canRent = true;
							findRoom = true;
							roomNumber = inn2.getRoomNumber();
						} else if (inn2.getLodgerId() == pc.getId()) {
							canRent = true;
							findRoom = true;
							roomNumber = inn2.getRoomNumber();
						} else {
							roomCount = (byte) (roomCount + 1);
						}
				}
				j++;
			}
			if (isRented) {
				pc.sendPackets((ServerBasePacket) new S_NPCTalkReturn(npc.getId(), "y_n_dragon6"));
			} else if (roomCount >= 16) {
				pc.sendPackets((ServerBasePacket) new S_NPCTalkReturn(npc.getId(), "y_n_dragon3"));
			} else if (canRent && !this.key_runout_doorid.contains(Integer.valueOf(npc.getId()))) {
				if (pc.getInventory().checkItem(40308, 300L * amount)) {
					L1Inn inn3 = InnTable.getInstance().getTemplate(npcId, roomNumber);
					if (inn3 != null) {
						Timestamp ts = new Timestamp(System.currentTimeMillis() + 7200000L);
						L1ItemInstance item2 = ItemTable.get().createItem(82504);
						if (item2 != null) {
							L1GroundInventory l1GroundInventory = null;
							item2.setKeyId(item2.getId());
							item2.setInnNpcId(npcId);
							item2.setHall(false);
							item2.setDueTime(ts);
							item2.setCount(amount);
							inn3.setKeyId(item2.getKeyId());
							inn3.setLodgerId(pc.getId());
							inn3.setHall(false);
							inn3.setDueTime(ts);
							InnTable.getInstance().updateInn(inn3);
							pc.getInventory().consumeItem(L1ItemId.ADENA, 300L * amount);
							L1Inventory inventory;
							if (pc.getInventory().checkAddItem(item2, amount) == L1Inventory.OK) {
								inventory = pc.getInventory();
							} else {
								inventory = World.get().getInventory(pc.getLocation());
							}
							inventory.storeItem(item2);
							if (InnKeyTable.checkey(item2)) {
								InnKeyTable.DeleteKey(item2);
								InnKeyTable.StoreKey(item2);
							} else {
								InnKeyTable.StoreKey(item2);
							}
							pc.sendPackets(
									(ServerBasePacket) new S_ServerMessage(143, npc.getName(), item2.getLogName()));
							pc.sendPackets((ServerBasePacket) new S_NPCTalkReturn(npc.getId(), "y_n_dragon2"));
							this.key_runout_doorid.add(Integer.valueOf(npc.getId()));
						}
					}
				} else {
					pc.sendPackets((ServerBasePacket) new S_NPCTalkReturn(npc.getId(), "y_n_dragon5"));
				}
			} else if (this.key_runout_doorid.contains(Integer.valueOf(npc.getId()))) {
				pc.sendPackets((ServerBasePacket) new S_NPCTalkReturn(npc.getId(), "y_n_dragon4"));
			}
		}
	}

	private void staraQuestA(L1NpcInstance npc, L1PcInstance pc) {
		try {
			int questid = ADLv80_3.QUEST.get_id();
			ArrayList<Integer> playerlist = this._DOORPLAYERMAP.get(Integer.valueOf(npc.getId()));
			if (playerlist == null)
				playerlist = new ArrayList<>();
//			if (playerlist.contains(Integer.valueOf(pc.getId()))) {
//				pc.sendPackets((ServerBasePacket) new S_BlueMessage(166, "\\f3逃离副本后无法再进入"));
//				pc.sendPacketsX8((ServerBasePacket) new S_SkillSound(pc.getId(), 7854));
//				SkillMode mode = L1SkillMode.get().getSkill(6799);
//				if (mode != null)
//					mode.start(pc, null, null, 43200);
//				pc.sendPackets((ServerBasePacket) new S_CloseList(pc.getId()));
//				return;
//			}
			playerlist.add(Integer.valueOf(pc.getId()));
			this._DOORPLAYERMAP.put(Integer.valueOf(npc.getId()), playerlist);
			QuestClass.get().startQuest(pc, ADLv80_3.QUEST.get_id());
			
			L1QuestUser quest = WorldQuest.get().put(pc.get_showId(), 1017, questid, pc);
			L1Teleport.teleport(pc, 32673, 32925, (short) 1017, 5, true);
			if (quest == null) {
				_log.error("副本设置过程发生异常!!");
				pc.sendPackets((ServerBasePacket) new S_CloseList(pc.getId()));
				return;
			}
			Integer time = QuestMapTable.get().getTime(1017);
			if (time != null)
				quest.set_time(time.intValue());
			L1SpawnUtil.spawnDoor(quest, 10037, 8011, 32675, 33182, (short) 1017, 0);
			L1SpawnUtil.spawnDoor(quest, 10038, 8015, 32687, 33125, (short) 1017, 1);
			L1SpawnUtil.spawnDoor(quest, 10039, 8015, 32729, 33180, (short) 1017, 1);
			
			
			L1SpawnUtil.spawn(pc.get_showId(), 8138, 32717, 32914, 1017, 0);
			Iterator<L1NpcInstance> iterator = quest.npcList().iterator();
			while (iterator.hasNext()) {
				L1NpcInstance npc2 = iterator.next();
				if (npc2 instanceof L1MonsterInstance) {
					L1MonsterInstance mob = (L1MonsterInstance) npc2;
					if (mob.getNpcId() >= 97204 && mob.getNpcId() <= 97209)
						continue;
					mob.set_storeDroped(true);
					mob.getInventory().clearItems();
				}
			}
			QuestClass.get().endQuest(pc, ADLv80_3.QUEST.get_id());
		} catch (Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		}
	}

	private boolean isError2(L1PcInstance pc, L1NpcInstance npc) {
		if (!pc.getInventory().checkItem(82504, 1L)) {
			pc.sendPackets((ServerBasePacket) new S_SystemMessage("身上必须要有龙门凭证才能进入。"));
			return true;
		}
		if (pc.getLevel() < 60) {
			pc.sendPackets((ServerBasePacket) new S_SystemMessage("等级未满60级，无法进入"));
			return true;
		}
		if (pc.hasSkillEffect(6799)) {
			pc.sendPackets((ServerBasePacket) new S_ServerMessage(1626));
			return true;
		}
		int users = QuestMapTable.get().getTemplate(1017);
		if (users == -1)
			users = 127;
		ArrayList<Integer> playerlist = this._DOORPLAYERMAP.get(Integer.valueOf(npc.getId()));
		if (playerlist != null && playerlist.size() >= users) {
			pc.sendPackets((ServerBasePacket) new S_SystemMessage("已达进入人数上限，无法进入"));
			return true;
		}
		return false;
	}
}
